<script setup>
import { watch } from 'vue'
import { ref, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import api from '@/api'
import { Message } from '@arco-design/web-vue'

const $route = useRoute()
const $router = useRouter()
const title = ref('')

const plan_id = $route.query.plan_id

// const data = ref([]);

// const addSon = (rowIndex) => {
//   data.value[rowIndex].son.push({
//     wenti: "问题2",
//     yaodian: "要点1",
//     putong: 1,
//     lianghao: 3,
//     youxiu: 5,
//   });
// };

// const deleteSon = (rowIndex, index) => {
//   data.value[rowIndex].son.splice(index, 1);
// };

const addItem = () => {
  form.recruit_template_id.push('')
  // data.value.push({
  //   bankuai: "",
  //   son: [
  //     {
  //       wenti: "",
  //       yaodian: "",
  //       putong: 1,
  //       lianghao: 3,
  //       youxiu: 5,
  //     },
  //   ],
  // });
}

const deleteItem = (rowIndex) => {
  form.recruit_template_id.splice(rowIndex, 1)
  handleTemplateChange(rowIndex, '')
}

const toJump = (url) => {
  console.log('router', $router.push(url))
  $router.push(url)
}

const goBack = () => {
  $router.go(-1)
}

// 评价详情
const form = reactive({
  plan_name: '',
  departments_id: '',
  posts_id: '',
  // post_ask: '',
  // recruit_number: '',
  recruit_template_id: [],
})

const formRef = ref(null)

const rules = {
  plan_name: [{ required: true, message: '请输入评价计划名称' }],
  departments_id: [{ required: true, message: '请选择评价部门' }],
  posts_id: [{ required: true, message: '请选择岗位名称' }],
  // recruit_number: [
  //   { required: true, message: '请输入评价人数' },
  //   { type: 'number', message: '请输入正确的评价人数', min: 1 },
  // ],
  // post_ask: [{ required: true, message: '请输入岗位要求' }],
  recruit_template_id: [
    { required: true, message: '请选择评价模板', trigger: 'change' },
    // { type: "array", message: "请选择评价模板", minLength: 1 },
  ],
}

// 部门数据
const departments = ref([])

// 岗位数据
const posts = ref([])

// 评价模板
const templates = ref([])

// 可选择的模板列表
const templateList = ref({
  pageInfo: {
    total: 0,
    currentPage: 1,
    totalPage: 1,
  },
  items: [
    // {
    //   "template_name": "评价模版23",
    //   "type": 2,
    //   "id": 22
    // },
  ],
})

// 展示模板内容
const templateArr = ref([])

// 保存
const handleSubmit = async () => {
  formRef.value.validate(async (valid) => {
    console.log(form)
    let data = JSON.parse(JSON.stringify(form))
    data.recruit_template_id = data.recruit_template_id.filter((item) => item)
    if (data.recruit_template_id.length == 0) {
      Message.error('请选择评价模板')
      return
    }
    let url = '/evaluate/createPlan'
    if (plan_id) {
      url = '/evaluate/updatePlan'
      data.plan_id = plan_id
    }
    data.recruit_template_id = data.recruit_template_id.join(',')
    console.log(data)
    const res = await api.post(url, data)
    if (res.code === 200) {
      Message.success('发布成功')
      if (plan_id) {
        toJump('/evaluate/plansDetails?id=' + plan_id)
      } else {
        toJump('/evaluate/plansList')
      }
    } else {
      Message.error(res.message)
    }
  })
}

// 部门列表
const getDepartments = async () => {
  console.log('获取部门列表')
  const res = await api.get('/evaluate/departmentsList')
  departments.value = res.data
  if (res.data.length > 0) {
    getPosts(res.data[0].id)
  }
}

// 岗位列表
const getPosts = async (departId) => {
  console.log('获取岗位列表' + departId)
  const res = await api.get(`/evaluate/postsList?department_id=${departId}`)
  posts.value = res.data
}

// 获取计划关联的评价模板
const getRecruitTemplate = async () => {
  const res = await api.get(`/evaluate/planTemplateDetails?plan_id=${plan_id}`)
  // templates.value = res.data;
  console.log(typeof res.data)
  form.recruit_template_id = res.data.map((item) => item.template_id)
  templateArr.value = res.data
}

const getTemplateLists = async (keyword = '') => {
  const res = await api.get(`/evaluate/templateAllList?keyword=${keyword}`)
  templateList.value = res.data.items
}

const getTemplateDetail = async (id) => {
  const res = await api.get(`/evaluate/templateDetail?template_id=${id}`)
  return res.data
}

const getDetail = async () => {
  console.log('获取评价计划详情', form)
  const res = await api.get(`/evaluate/evaluatePlanDetails?plan_id=${plan_id}`)
  // form = reactive(res.data)
  form.id = res.data.id
  form.plan_name = res.data.plan_name
  form.departments_id = res.data.departments_id
  form.posts_id = res.data.posts_id
  form.post_ask = res.data.post_ask
  form.recruit_number = res.data.recruit_number + ''

  console.log('form', form)
}

const init = async () => {
  console.log('加载收据')
  await getDepartments()
  getTemplateLists()
  if (plan_id) {
    getDetail()
    getRecruitTemplate()
  } else {
    // form.recruit_template_id.push('');
  }
}

watch(
  () => form.departments_id,
  (newVal) => {
    console.log('change departments_id', newVal)
    posts.value = []
    getPosts(newVal)
  }
)

const changeDepartments = async (e) => {
  form.posts_id = ''
}

const handleTemplateChange = async (index, value) => {
  console.log('change template', index, value)
  if (!value) {
    templateArr.value.splice(index, 1)
    return
  }
  const content = await getTemplateDetail(value)
  templateArr.value[index] = content
  formRef.value.clearValidate(['recruit_template_id'])
  console.log('templateArr', templateArr.value)
}

init()
</script>

<template>
  <div class="page">
    <div class="header">{{ plan_id ? '更新' : '发布' }}评价计划</div>

    <div class="record_body">
      <div class="form_body">
        <a-form ref="formRef" auto-label-width :model="form" :rules="rules">
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item field="departments_id" label="评价计划名称">
                <a-input placeholder="请输入评价计划名称" v-model="form.plan_name"></a-input>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item field="departments_id" label="评价部门">
                <a-select
                  v-model="form.departments_id"
                  placeholder="请选择评价部门"
                  allow-clear
                  @change="changeDepartments"
                >
                  <a-option
                    v-for="item in departments"
                    :key="item.id"
                    :value="item.id"
                    >{{ item.name }}</a-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item field="posts_id" label="评价岗位名称">
                <a-select
                  v-model="form.posts_id"
                  placeholder="请选择评价岗位名称"
                  allow-clear
                >
                  <a-option
                    v-for="item in posts"
                    :key="item.id"
                    :value="item.id"
                    >{{ item.name }}</a-option
                  >
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          
          <template
            v-for="(item, index) in form.recruit_template_id"
            :key="index"
          >
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item field="recruit_template_id" label="评价模板">
                  <a-select
                    v-model="form.recruit_template_id[index]"
                    placeholder="请选择评价模板"
                    @change="handleTemplateChange(index, $event)"
                    allow-search
                    @search="getTemplateLists"
                    allow-clear
                  >
                    <a-option
                      v-for="item in templateList"
                      :key="item.id"
                      :value="item.id"
                      >{{ item.template_name }}</a-option
                    >
                    <!-- <template #footer>
                      <a-pagination
                        :total="templateList.pageInfo.total"
                        show-total
                        simple
                        :default-page-size="5"
                        @change="getTemplateLists"
                      ></a-pagination>
                    </template> -->
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="12" v-if="index > 0">
                <a-button
                  type="primary"
                  status="danger"
                  size="small"
                  @click="deleteItem(index)"
                  >删除模板</a-button
                >
              </a-col>
            </a-row>

            <a-row :gutter="24" v-if="templateArr[index]">
              <a-col :span="24">
                <div>
                  <div class="flex">
                    <div class="table_name">岗位画像配置</div>
                    <div class="table_body">
                      <a-table
                        :data="templateArr[index].content"
                        :pagination="false"
                        :bordered="{ headerCell: true, cell: true }"
                      >
                        <template #columns>
                          <a-table-column
                            title="板块"
                            align="center"
                            data-index="plate_name"
                          >
                            <template #cell="{ record, rowIndex }">
                              <div class="flex at_c">
                                <!-- <a-button type="primary"
                              status="danger"
                              size="mini"
                              @click="deleteItem(rowIndex)">删除板块</a-button> -->

                                <a-input v-model="record.plate_name" />

                                <!-- <a-button type="primary"
                              size="mini"
                              @click="addSon(rowIndex)">增加问题</a-button> -->
                              </div>
                            </template>
                          </a-table-column>
                          <a-table-column
                            title="问题"
                            align="center"
                            data-index="problem"
                          >
                            <template #cell="{ record }">
                              <div
                                class="diytd"
                                v-for="(item, index) in record.son"
                                :key="index"
                              >
                                <a-textarea v-model="item.problem" />
                              </div>
                            </template>
                          </a-table-column>
                          <a-table-column
                            title="考核要点"
                            align="center"
                            data-index="examine"
                          >
                            <template #cell="{ record }">
                              <div
                                class="diytd"
                                v-for="(item, index) in record.son"
                                :key="index"
                              >
                                <a-textarea v-model="item.examine" />
                              </div>
                            </template>
                          </a-table-column>
                          <a-table-column title="分值">
                            <a-table-column
                              title="普通"
                              align="center"
                              :width="70"
                              data-index="ordinary"
                            >
                              <template #cell="{ record }">
                                <div
                                  class="diytd"
                                  v-for="(item, index) in record.son"
                                  :key="index"
                                >
                                  <div class="h32 jc_c">
                                    {{ item.ordinary }}
                                  </div>
                                </div>
                              </template>
                            </a-table-column>
                            <a-table-column
                              title="良好"
                              align="center"
                              :width="70"
                              data-index="good"
                            >
                              <template #cell="{ record }">
                                <div
                                  class="diytd"
                                  v-for="(item, index) in record.son"
                                  :key="index"
                                >
                                  <div class="h32 jc_c">{{ item.good }}</div>
                                </div>
                              </template>
                            </a-table-column>
                            <a-table-column
                              title="优秀"
                              align="center"
                              :width="70"
                              data-index="excellent"
                            >
                              <template #cell="{ record }">
                                <div
                                  class="diytd"
                                  v-for="(item, index) in record.son"
                                  :key="index"
                                >
                                  <div class="h32 jc_c">
                                    {{ item.excellent }}
                                  </div>
                                </div>
                              </template>
                            </a-table-column>
                          </a-table-column>

                          <!-- <a-table-column title="操作"
                              align="right"
                              :width="100">
                <template #cell="{ record,rowIndex }">
                  <div class="diytd"
                      v-for="(item,index) in record.son"
                      :key="index">
                    <div class="h32">
                      <a-button type="primary"
                                status="danger"
                                size="mini"
                                @click="deleteSon(rowIndex,index)">删除问题</a-button>
                    </div>
                  </div>
                </template>
              </a-table-column> -->
                        </template>
                      </a-table>
                    </div>
                  </div>
                  <div class="table_bottom">
                    <div class="name">合计</div>
                    <div style="flex: 1">
                      板块：{{ templateArr[index].plate_number }}
                    </div>
                    <div style="flex: 1">
                      问题：{{ templateArr[index].problem_number }}
                    </div>
                    <div style="flex: 1">
                      总分：{{ templateArr[index].score }}
                    </div>
                  </div>
                </div>
              </a-col>
            </a-row>
            <div class="mb30"></div>
          </template>

          <div v-if="!form.recruit_template_id.length" class="mt30 mb30">
            <a-button @click="addItem" type="primary">添加评价模板</a-button>
          </div>

          <!-- <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item field="muban" label="评价模板">
                <a-select
                  v-model="form.muban"
                  placeholder="请选择评价模板"
                  allow-clear
                >
                  <a-option value="section one">模板一</a-option>
                  <a-option value="section two">模板二</a-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row> -->

          <div class="flex at_c jc_e">
            <a-space>
              <a-button type="primary" status="danger" @click="goBack"
                >取消</a-button
              >
              <a-button type="primary" @click="handleSubmit">确认发布</a-button>
            </a-space>
          </div>
        </a-form>
      </div>
    </div>
  </div>
</template>

<style scoped>
.page {
  height: 95%;
  border-bottom: 0;
}

.header {
  height: 52px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: bold;
}

:deep(.arco-table-cell):has(.diytd) {
  padding: 0;
}
:deep(.arco-table-cell):has(.diytd) .diytd {
  padding: 0.6rem 1.06667rem;
  border-bottom: 1px solid #ddd;
}
:deep(.arco-table-cell):has(.diytd) .diytd:last-child {
  border: none;
}

.diytd {
  height: 80px;
  display: flex;
  align-items: center;
}

.h32 {
  height: 32px;
  display: flex;
  align-items: center;
}

.table_name {
  width: 100px;
  box-sizing: border-box;
  padding: 0 40px;
  font-size: 14px;
  background-color: #f2f3f5;
  display: flex;
  align-items: center;
  justify-content: center;
  border-top: 1px solid #e5e6eb;
  border-left: 1px solid #e5e6eb;
  border-bottom: 1px solid #e5e6eb;
}

.table_body {
  width: 100%;
}

.table_bottom {
  display: flex;
  align-items: center;
  background-color: #f2f3f5;
  border-left: 1px solid #e5e6eb;
  border-right: 1px solid #e5e6eb;
  border-bottom: 1px solid #e5e6eb;
}

.table_bottom > div {
  box-sizing: border-box;
  padding: 0.6rem 1.06667rem;
  text-align: center;
}

.table_bottom > div:not(:last-child) {
  border-right: 1px solid #e5e6eb;
}

.table_bottom .name {
  width: 100px;
}

.record_body {
  box-sizing: border-box;
  padding: 20px 24px;
}

.form_body {
  box-sizing: border-box;
  padding: 20px 24px;
  background-color: #fff;
  margin-bottom: 20px;
}
</style>
